﻿using System.Collections;
using System.Reflection;
using System.Xml;

namespace Gonte.Xml.Serialization
{
    public class XmlDictionarySerializer
        : XmlCollectionSerializer
    {
        protected internal XmlDictionarySerializer(object @object)
            : base(@object)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="context"></param>
        public override void Serialize(XmlWriter writer, XmlSerializationContext context)
        {
            ExceptionThrower.ThrowWhenNull("context", context);

            string elementName = GetElementName(context);
            writer.WriteStartElement(elementName);

            IDictionary dictionary = object_ as IDictionary;

            TypeXmlMapping typeXmlMapping = TypeXmlMapping.GetMapping(object_.GetType());

            foreach (object value in dictionary.Values)
            {
                XmlSerializationContext childContext = new XmlSerializationContext();

                object parent = context.Parent;
                PropertyInfo propertyInfo = parent.GetType().GetProperty(context.PropertyName);
                childContext.PropertyName = context.PropertyName;
                childContext.Attributes = context.Attributes;
                childContext.Level = ++context.Level;
                childContext.SerializeType = typeXmlMapping.IsAbstractType;
                childContext.Parent = object_;

                XmlObjectSerializer serializer = XmlObjectSerializer.GetSerializer(value);
                serializer.Serialize(writer, childContext);
            }

            writer.WriteEndElement();
        }
    }
}
